package com.common.print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ReentrantLockDemo
 * @Description TODO
 * @Author admin
 * @Date 2021/4/28 15:44
 * @Version 1.0
 **/
public class ReentrantLockDemo {

    /**
     * @Description: Condition.await方法相当与Object.wait方法 Condition.single方法相当于Object.notify方法
     * Condition的强大之处在于他能细粒度的控制多线程的休眠与唤醒；对于同一个锁，我们可以创建多个Condition，在不同的情况下使用不同的Condition
     * @Author: liuhuanjin
     * @Date: 2021/4/28 15:59
     **/
    private static int num = 1;
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();

        Thread threadA =  new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        lock.lock();
                        while (num != 1){
                            conditionA.await();
                        }
                        System.out.println("A");
                        num = 2;
                        conditionB.signal();
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });

        Thread threadB =  new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        lock.lock();
                        while (num != 2){
                            conditionB.await();
                        }
                        System.out.println("B");
                        num = 3;
                        conditionC.signal();
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });

        Thread threadC =  new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        lock.lock();
                        while (num != 3){
                            conditionC.await();
                        }
                        System.out.println("C");
                        num = 1;
                        conditionA.signal();
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();

    }

}
